#!/usr/bin/env node

import { execSync, spawn } from 'child_process';
import { fileURLToPath } from 'url';
import { dirname, resolve } from 'path';
import { existsSync } from 'fs';
import readline from 'readline';

const __dirname = dirname(fileURLToPath(import.meta.url));
const rootDir = resolve(__dirname, '../..');
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

// 颜色输出定义
const colors = {
  reset: '\x1b[0m',
  green: '\x1b[32m',
  blue: '\x1b[34m',
  yellow: '\x1b[33m',
  red: '\x1b[31m',
  cyan: '\x1b[36m'
};

// 打印带颜色的消息
function log(message, color = 'reset') {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

// 检查Node版本
function checkNodeVersion() {
  try {
    const nodeVersion = execSync('node --version').toString().trim();
    log(`📋 Node版本: ${nodeVersion}`, 'blue');
  } catch (error) {
    log('❌ Node.js未安装，请先安装Node.js', 'red');
    process.exit(1);
  }
}

// 检查pnpm
function checkPnpm() {
  try {
    const pnpmVersion = execSync('pnpm --version').toString().trim();
    log(`📋 pnpm版本: ${pnpmVersion}`, 'blue');
    return true;
  } catch (error) {
    log('❌ pnpm未安装，请先安装pnpm: npm install -g pnpm', 'red');
    return false;
  }
}

// 执行命令并处理错误
function runCommand(command, description, isVerbose = true) {
  log(`\n${description}...`, 'cyan');
  try {
    const options = isVerbose ? { stdio: 'inherit' } : { stdio: ['ignore', 'pipe', 'inherit'] };
    execSync(command, options);
    log(`✅ ${description}完成!`, 'green');
    return true;
  } catch (error) {
    log(`❌ ${description}失败!`, 'red');
    log(`错误信息: ${error.message}`, 'red');
    return false;
  }
}

// 检查并创建构建目录
async function checkBuildDir() {
  const buildDir = resolve(rootDir, 'dist');
  if (!existsSync(buildDir)) {
    try {
      log('📁 创建构建输出目录...', 'yellow');
      const fs = await import('fs').then(m => m.promises);
      await fs.mkdir(buildDir, { recursive: true });
      log('✅ 构建输出目录创建成功!', 'green');
    } catch (error) {
      log('⚠️ 创建构建输出目录失败，但继续执行构建...', 'yellow');
    }
  }
}

// 构建共享库
function buildShared() {
  return runCommand('pnpm run build:shared', '🔨 构建共享库 (shared 和 configs)');
}

// 构建单个微应用
function buildMicroApp(app) {
  return runCommand(
    `pnpm --prefix ${app.path} run build`,
    `🔧 构建 ${app.name}`
  );
}

// 构建所有微应用
function buildMicroApps() {
  log('\n🚀 开始构建微应用...', 'blue');
  
  const microApps = [
    { name: '认证微应用', path: 'packages/micro-auth' },
    { name: '仪表板微应用', path: 'packages/micro-dashboard' },
    { name: '用户微应用', path: 'packages/micro-user' }
  ];
  
  let allSuccess = true;
  
  for (const app of microApps) {
    const success = buildMicroApp(app);
    if (!success) allSuccess = false;
  }
  
  return allSuccess;
}

// 构建主应用
function buildHostApp() {
  return runCommand(
    'pnpm --prefix apps/microfrontend-host run build',
    '🏗️ 构建主应用 (microfrontend-host)'
  );
}

// 构建场景定义
const buildScenarios = {
  all: {
    name: '完整构建',
    description: '构建共享库、所有微应用和主应用',
    async execute() {
      const sharedSuccess = buildShared();
      if (!sharedSuccess) return { sharedSuccess, microAppsSuccess: false, hostSuccess: false };
      
      const microAppsSuccess = buildMicroApps();
      const hostSuccess = buildHostApp();
      
      return { sharedSuccess, microAppsSuccess, hostSuccess };
    }
  },
  minimal: {
    name: '最小化构建',
    description: '构建共享库和主应用',
    async execute() {
      const sharedSuccess = buildShared();
      if (!sharedSuccess) return { sharedSuccess, microAppsSuccess: false, hostSuccess: false };
      
      const hostSuccess = buildHostApp();
      
      return { sharedSuccess, microAppsSuccess: true, hostSuccess };
    }
  },
  hostOnly: {
    name: '仅主应用',
    description: '仅构建主应用',
    async execute() {
      const sharedSuccess = buildShared();
      if (!sharedSuccess) return { sharedSuccess, microAppsSuccess: false, hostSuccess: false };
      
      const hostSuccess = buildHostApp();
      
      return { sharedSuccess, microAppsSuccess: true, hostSuccess };
    }
  },
  sharedOnly: {
    name: '仅共享库',
    description: '仅构建共享库',
    async execute() {
      const sharedSuccess = buildShared();
      
      return { sharedSuccess, microAppsSuccess: true, hostSuccess: true };
    }
  },
  microOnly: {
    name: '仅微应用',
    description: '构建共享库和所有微应用',
    async execute() {
      const sharedSuccess = buildShared();
      if (!sharedSuccess) return { sharedSuccess, microAppsSuccess: false, hostSuccess: false };
      
      const microAppsSuccess = buildMicroApps();
      
      return { sharedSuccess, microAppsSuccess, hostSuccess: true };
    }
  },
  custom: {
    name: '自定义构建',
    description: '选择要构建的应用',
    async execute() {
      return new Promise((resolve) => {
        log('\n📋 选择要构建的部分:', 'blue');
        log('1. 共享库', 'blue');
        log('2. 微应用', 'blue');
        log('3. 主应用', 'blue');
        log('4. 组合选择', 'blue');
        
        rl.question('请选择 (1-4): ', async (choice) => {
          let sharedSuccess = true;
          let microAppsSuccess = true;
          let hostSuccess = true;
          
          switch (choice) {
            case '1':
              sharedSuccess = buildShared();
              break;
            case '2':
              sharedSuccess = buildShared();
              if (sharedSuccess) {
                microAppsSuccess = buildMicroApps();
              } else {
                microAppsSuccess = false;
              }
              break;
            case '3':
              sharedSuccess = buildShared();
              if (sharedSuccess) {
                hostSuccess = buildHostApp();
              } else {
                hostSuccess = false;
              }
              break;
            case '4':
              // 更复杂的组合选择逻辑可以在这里实现
              log('🚧 组合选择功能待实现，将执行完整构建', 'yellow');
              sharedSuccess = buildShared();
              if (sharedSuccess) {
                microAppsSuccess = buildMicroApps();
                hostSuccess = buildHostApp();
              } else {
                microAppsSuccess = false;
                hostSuccess = false;
              }
              break;
            default:
              log('❌ 无效选择，将执行完整构建', 'yellow');
              sharedSuccess = buildShared();
              if (sharedSuccess) {
                microAppsSuccess = buildMicroApps();
                hostSuccess = buildHostApp();
              } else {
                microAppsSuccess = false;
                hostSuccess = false;
              }
          }
          
          resolve({ sharedSuccess, microAppsSuccess, hostSuccess });
        });
      });
    }
  }
};

// 显示构建总结
function showBuildSummary(results) {
  log('\n📊 构建总结:', 'blue');
  log(`  - 共享库: ${results.sharedSuccess ? '✅ 成功' : '❌ 失败'}`, results.sharedSuccess ? 'green' : 'red');
  log(`  - 微应用: ${results.microAppsSuccess ? '✅ 成功' : '❌ 失败'}`, results.microAppsSuccess ? 'green' : 'red');
  log(`  - 主应用: ${results.hostSuccess ? '✅ 成功' : '❌ 失败'}`, results.hostSuccess ? 'green' : 'red');
  
  if (results.sharedSuccess && results.microAppsSuccess && results.hostSuccess) {
    log('\n🎉 项目构建全部完成!', 'green');
    log('\n💡 提示:', 'blue');
    log('  - 所有构建产物都在各自的dist目录下', 'blue');
    log('  - 可以使用 pnpm --prefix apps/microfrontend-host run preview 预览主应用', 'blue');
    return true;
  } else {
    log('\n⚠️ 项目构建部分失败，请查看错误信息', 'yellow');
    return false;
  }
}

// 智能构建主函数
async function smartBuild() {
  try {
    log('🎯 智能构建工具\n', 'green');
    
    // 环境检查
    checkNodeVersion();
    if (!checkPnpm()) {
      process.exit(1);
    }
    
    // 检查构建目录
    await checkBuildDir();
    
    // 显示构建选项
    log('📋 选择构建模式:');
    log('1. 完整构建 (共享库 + 所有微应用 + 主应用)');
    log('2. 最小化构建 (共享库 + 主应用)');
    log('3. 仅主应用');
    log('4. 仅共享库');
    log('5. 仅微应用 (共享库 + 所有微应用)');
    log('6. 自定义构建');
    
    // 等待用户选择
    rl.question('请选择 (1-6): ', async (choice) => {
      let selectedScenario;
      
      switch (choice) {
        case '1':
          selectedScenario = buildScenarios.all;
          break;
        case '2':
          selectedScenario = buildScenarios.minimal;
          break;
        case '3':
          selectedScenario = buildScenarios.hostOnly;
          break;
        case '4':
          selectedScenario = buildScenarios.sharedOnly;
          break;
        case '5':
          selectedScenario = buildScenarios.microOnly;
          break;
        case '6':
          selectedScenario = buildScenarios.custom;
          break;
        default:
          log('使用默认模式: 完整构建', 'yellow');
          selectedScenario = buildScenarios.all;
      }
      
      log(`\n🔄 执行 ${selectedScenario.name}: ${selectedScenario.description}...\n`);
      
      // 执行选择的构建场景
      const results = await selectedScenario.execute();
      
      // 显示构建总结
      const allSuccess = showBuildSummary(results);
      
      // 关闭readline接口
      rl.close();
      
      // 根据构建结果设置退出码
      process.exit(allSuccess ? 0 : 1);
    });
    
  } catch (error) {
    log('\n❌ 构建过程中发生未预期的错误:', 'red');
    log(error.message, 'red');
    rl.close();
    process.exit(1);
  }
}

// 执行主函数
// 启动智能构建
smartBuild();